import React, { useState } from 'react'
import { Card, Row, Col, Button, Table, Tag } from 'antd'
import { useRequest, useMount } from 'ahooks'
import moment from 'moment'

import NewContract from '@/pages/Dashboard/components/CrossChain/pages/Contract/List/components/New'
import { listContracts } from '@/pages/Dashboard/components/CrossChain/service'
import { CROSS_CHAIN_CONTRACT_STATUS } from '@/pages/Dashboard/components/CrossChain/enums'

import { checkPermission } from '@/components/AuthComponent/utils'
// import { AuthenticatedLink } from '@/components/AuthLink'

import './index.less'
const searchOption = {
  page: 1,
  per_page: 10,
  name: '',
}

const ContractList = () => {
  const [modalVisible, setModalVisible] = useState(false)
  const [contracts, setContracts] = useState([])
  const [total, setTotal] = useState(0)
  const { loading: loadingContracts, run: loadContracts } = useRequest(listContracts, { manual: true })
  const columns = [
    {
      title: '合约名称',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '合约ID',
      dataIndex: 'id',
      key: 'id',
    },
    {
      title: '创建时间',
      dataIndex: 'created_at',
      key: 'created_at',
      render: (v) => v ? moment(v).format('YYYY-MM-DD HH:mm:ss') : '--',
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (text) => <Tag color={CROSS_CHAIN_CONTRACT_STATUS[text].status}>{CROSS_CHAIN_CONTRACT_STATUS[text].label}</Tag>,
    },
    // {
    //   title: '下载',
    //   dataIndex: 'url',
    //   key: 'url',
    //   render: (text, record) => <AuthenticatedLink url={text} filename={`${record.id}.class`}>下载</AuthenticatedLink>,
    // },
  ]
  const queryContracts = async(params = {}) => {
    try {
      const res = await loadContracts({
        ...params,
        ...searchOption,
      })
      const { data: { data: contracts, total }} = res
      setTotal(total)
      setContracts(contracts)
    } catch (e) {
      console.error(e)
    }
  }

  useMount(() => {
    queryContracts()
  })

  const handleTableChange = (pagination) => {
    const { current: page, pageSize: perPage } = pagination
    searchOption.page = page
    searchOption.perPage = perPage
    queryContracts()
  }
  const onCreateSuccess = () => {
    setModalVisible(false)
    searchOption.page = 1
    queryContracts()
  }

  // const onSearch = (value) => {
  //   searchOption.name = value
  //   searchOption.page = 1
  //   queryContracts()
  // }

  return (
    <div>
      <Card style={{ marginTop: 24 }}>
        <Row style={{ marginBottom: 18 }}>
          <Col span={8}>
            {
              checkPermission('cross-chain-contracts-create', 'POST') &&
              <Button type="primary" onClick={() => setModalVisible(true)}>
                新建合约
              </Button>
            }
          </Col>
          {/* <Col span={16} style={{ textAlign: 'right' }}>
            <Search allowClear onSearch={onSearch} className="search" placeholder="输入合约名称" style={{ width: 260 }} />
          </Col> */}
        </Row>
        <Table
          loading={loadingContracts}
          dataSource={contracts}
          columns={columns}
          rowKey="id"
          onChange={handleTableChange}
          pagination={{
            current: searchOption.page,
            pageSize: searchOption.per_page,
            position: ['bottomCenter'],
            showTotal: (total, range) => `共 ${total} 条记录 第 ${range[0]}-${range[1]} 项`,
            showSizeChanger: true,
            showQuickJumper: true,
            total,
          }}
        />
      </Card>
      <NewContract visible={modalVisible} onCancel={() => setModalVisible(false)} onSuccess={onCreateSuccess} />
    </div>
  )
}

export default ContractList
